﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Knihotoc_WP8.CustomControls;
using Knihotoc_WP8.Settings;
using System.Windows.Media;
using Knihotoc_WP8.Data;
using Knihotoc_WP8.Data.Storage;
using System.Windows.Input;
using System.Device.Location;

namespace Knihotoc_WP8.Pages
{
    public partial class MainPage : PhoneApplicationPage
    {
        private int booksListsLoaded;
        private LoggedInUserData loggedInUserData;
        UnregisteredUserData unregisteredUserData;

        // Constructor
        public MainPage()
        {
            this.InitializeComponent();

            booksListsLoaded = 0;

            currentPositionPushpin.Template = (ControlTemplate)(App.Current.Resources["PushpinCurrentPosition"]);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (this.NavigationContext.QueryString.ContainsKey("CollectibleName"))
            {
                string collectibleName = NavigationContext.QueryString["CollectibleName"];
            }

            User loggedUser = IsolatedStorageHandler.Instance.GetValueOrDefault<User>("Logged_user", null);

            if (loggedUser == null)
            {
                UnregisteredUserData unregUserData = new UnregisteredUserData();
                unregUserData.UserLoggedIn += unregisteredUserData_UserLoggedIn;
                this.userDataGrid.Children.Add(unregUserData);
            }
            else
            {
                loggedInUserData = new LoggedInUserData(loggedUser);
                this.userDataGrid.Children.Add(loggedInUserData);
            }            

            CurrentSettings.Instance.CurrentPositionChanged += CurrentSettings_CurrentPositionChanged;
            this.currentPositionPushpin.Location = CurrentSettings.Instance.CurrentPosition;

            this.map.Center = this.currentPositionPushpin.Location;
            this.map.ZoomLevel = DefaultSettings.Instance.MapZoomLevel;            
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            CurrentSettings.Instance.CurrentPositionChanged -= CurrentSettings_CurrentPositionChanged;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            throw new Exception("Exit application");
        }        

        void userLoaded()
        {
            // update content of fields
            loggedInUserData = new LoggedInUserData(CurrentSettings.Instance.User);
            loggedInUserData.ShowAllMyBooks += new EventHandler(this.UserData_ShowAllMyBooks);
            this.userDataGrid.Children.Clear();
            this.userDataGrid.Children.Add(loggedInUserData);
            // save new data to iso_storage
            IsolatedStorageHandler.Instance.AddOrUpdateValue("Logged_user", CurrentSettings.Instance.User);
        }

        void booksLoaded()
        {
            // save new data to iso_storage
            IsolatedStorageHandler.Instance.AddOrUpdateValue("Logged_user", CurrentSettings.Instance.User);
            loggedInUserData.reloadValues();
        }

        void CurrentSettings_CurrentPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            this.currentPositionPushpin.Location = e.Position.Location;
            this.map.Center = this.currentPositionPushpin.Location;
            this.map.ZoomLevel = DefaultSettings.Instance.MapZoomLevel;
            UpdatePrecision(e.Position.Location);
        }

        private void UpdatePrecision(GeoCoordinate location)
        {
            precision.Visibility = Visibility.Collapsed;
            if (location == null)
                return;

            precision.Visibility = Visibility.Visible;
            precision.Locations = new Microsoft.Phone.Controls.Maps.LocationCollection();

            var earthRadius = 6371;
            var lat = location.Latitude * Math.PI / 180.0; //radians
            var lon = location.Longitude * Math.PI / 180.0; //radians
            var d = location.HorizontalAccuracy / 1000 / earthRadius; // d = angular distance covered on earths surface

            for (int x = 0; x <= 360; x++)
            {
                var brng = x * Math.PI / 180.0; //radians 
                var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));
                var lngRadians = lon + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));

                var pt = new GeoCoordinate(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);
                precision.Locations.Add(pt);
            }
        }

        private void UserData_ShowAllMyBooks(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookListPage.xaml", UriKind.Relative));
        }

        private void Map_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/MapPage.xaml", UriKind.Relative));
        }

        private void CommonPlaceItemTemplate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int placeID = ((GridID)sender).ID;

            NavigationService.Navigate(new Uri("/Pages/CommonPlaceDetailPage.xaml?PlaceID=" + placeID.ToString(), UriKind.Relative));
        }

        private void AllPlacesButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/CommonPlaceListPage.xaml", UriKind.Relative));
        }

        private void TestDatabase_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                //client.GetBookNameByIDCompleted += client_GetBookByNameByIDCompleted;
                //client.GetBookNameByIDAsync(0);
                //client.GetBookByIDCompleted += client_GetBookByIDCompleted;
                //client.GetBookByIDAsync(5);
                //client.GetBooksInLocationCompleted += client_GetBooksInLocationCompleted;
                //client.GetBooksInLocationAsync(0, 0, 1, null);
                /*client.GetUserBooksCompleted += client_GetUserBooksCompleted;
                client.GetUserBooksAsync(2);
                client.GetBorrowedBooksCompleted += client_GetBorrowedBooksCompleted;
                client.GetBorrowedBooksAsync(1);*/

            }
            catch (System.ServiceModel.CommunicationException)
            {
            }
        }

        private void switchUserButton_Click_1(object sender, RoutedEventArgs e)
        {
            this.userDataGrid.Children.Clear();
            unregisteredUserData = new UnregisteredUserData();
            unregisteredUserData.UserLoggedIn += unregisteredUserData_UserLoggedIn;

            this.userDataGrid.Children.Add(unregisteredUserData);

            // navigate to the panorama item that we want (user login)
            this.panorama.SetValue(Panorama.SelectedItemProperty, this.panorama.Items[0]);
            this.panorama.Measure(new Size());
        }

        void unregisteredUserData_UserLoggedIn(object sender, EventArgs e)
        {
            userLoaded();

            this.userDataGrid.Children.Clear();
        }

        private void Map_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/MapPage.xaml", UriKind.Relative));
        }

        private void Map_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/MapPage.xaml", UriKind.Relative));
        }

        private void Map_Pan(object sender, Microsoft.Phone.Controls.Maps.MapDragEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/MapPage.xaml", UriKind.Relative));
        }

        private void Map_Zoom(object sender, Microsoft.Phone.Controls.Maps.MapZoomEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/MapPage.xaml", UriKind.Relative));
        }
    }
}